package com.product.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @program: Member_Perks_Store
 * @description: spring获取bean工具类
 * @author: 无恙
 * @create: 2024-06-20 23:05
 **/

@Component
public class SPUtil implements ApplicationContextAware {
    // 将管理上下文的 applicationContext 设置成静态变量，供全局调用
    private static volatile ApplicationContext applicationContext;

    // 获取已经实例化的 bean 方法
    public static <T> T getBean(Class<T> c) {
        if (applicationContext == null) {
            throw new IllegalStateException("ApplicationContext is not initialized yet.");
        }
        return applicationContext.getBean(c);
    }

    @Override
    public synchronized void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (SPUtil.applicationContext == null) {
            SPUtil.applicationContext = applicationContext;
        }
    }
}
